package com.century.sjt.util;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.EMChat.db.TranslateDao;
import com.century.sjt.activity.wallet.TranslateActivity;
import com.century.sjt.activity.wallet.TranslateShopActivity;
import com.century.sjt.utils.PreferenceManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.century.sjt.EMChat.domain.Translate;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

/**
 * 百度翻译引擎
 */
public class BaiduTranslate {
	private static final String UTF8 = "utf-8";

	//申请者开发者id，实际使用时请修改成开发者自己的appid
	private static final String appId = "20160804000026263";

	//申请成功后的证书token，实际使用时请修改成开发者自己的token
	private static final String token = "anj5_pYK7Z3t5WwgsboT";

	//随机数，用于生成md5值，开发者使用时请激活下边第四行代码
	private static final Random random = new Random();
	//翻译监听
	private TranslateListItemClickListener listener;
	private String userId,isTrans,transLanguage,isMerchant;
	private String transLanguageName,transBaiduCode;
	public void translate(final Context mContext, RequestQueue mQueue, final EMMessage message, final String from, final String to){
		SharedPreferences mainSharedPreferences = mContext. getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
		userId = mainSharedPreferences.getString("userId", "");
		isMerchant = mainSharedPreferences.getString("isMerchant", "");
		isTrans = mainSharedPreferences.getString("isTrans","");
		transLanguage = mainSharedPreferences.getString("transLanguage","");
		transBaiduCode = mainSharedPreferences.getString("transBaiduCode","");
		transLanguageName = mainSharedPreferences.getString("transLanguageName","");
		//生成随机数
		final int salt = random.nextInt(10000);
		String md5;//用于md5加密
		//获取翻译内容
		TextMessageBody txtBody = (TextMessageBody) message.getBody();
		final String textMessage =txtBody.getMessage();
		textMessage.replaceAll("\\s*","");
		textMessage.replaceAll("\\[.{2,3}\\]", "[表情]");
		String text = textMessage;
//
		Locale locale = mContext.getResources().getConfiguration().locale;
		String language = locale.getLanguage();
		//判断翻译语言对象
		if ("".equals(transBaiduCode)||"null".equals(transBaiduCode)||null==transBaiduCode){
			language = "auto";//如果未设置自动翻译语言
		}else {
			language = transBaiduCode;
		}
		String md5src = appId+text+salt+token;
		try {
			String utfcode = URLDecoder.decode(md5src,UTF8);
			md5 = MD5.MD5(utfcode);//MD5加密
		}catch (UnsupportedEncodingException ex) {
			throw new RuntimeException("Broken VM does not support UTF-8");
		}
		//请求
//		language = "en";
		final String translateUrl = "http://api.fanyi.baidu.com/api/trans/vip/translate?q="+text+"&from=auto&to="+language
				+ "&appid="+appId+"&salt="+salt+"&sign="+md5.toLowerCase();

		if ("1".equals(isTrans)){
//			if (PreferenceManager.getInstance().getLanguageCode().equals(message.getStringAttribute("languageCode",null))){
//
//			}else {
//
//			}
			Translate(translateUrl,mContext,mQueue,message,from,language);
		}else {
			//询问是否取消
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setMessage(mContext.getString(R.string.text_noopen_translate));
			builder.setPositiveButton(mContext.getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					if ("0".equals(isMerchant)){
						Intent intent =new Intent();
						intent.setClass(mContext, TranslateActivity.class);
						mContext.startActivity(intent);

					}else {
						Intent intent =new Intent();
						intent.setClass(mContext, TranslateShopActivity.class);
						mContext.startActivity(intent);
					}
				}
			});
			builder.setNegativeButton(mContext.getResources().getString(R.string.btn_no), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.setCancelable(false);
			builder.create().show();
		}

	}
	public void setTranslateListItemClickListener(TranslateListItemClickListener listener) {
		this.listener = listener;
	}
	public interface TranslateListItemClickListener{
		/**
		 * 翻译事件监听
		 * @param message
		 * @return
		 */
		void onSaveClick(Translate message);
		void onUpdateClick(Translate message);
		void onDeleteClick(Translate message);
	}

	private void Translate(String translateUrl,final Context mContext, RequestQueue mQueue, final EMMessage message, final String from, final String to){
		StringRequest stringRequest = new StringRequest(Request.Method.POST,translateUrl, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				try {
//					TipUtil.log("接口成功返回", response.toString(), 1);
					JSONTokener jsonParser = new JSONTokener(response);
					JSONObject res = (JSONObject) jsonParser.nextValue();
					String from = res.getString("from");
					String to = res.getString("to");
					JSONArray trans_result = res.getJSONArray("trans_result");
					for (int i = 0;i<trans_result.length();i++){
						JSONObject trans = (JSONObject) trans_result.getJSONObject(i);
						String src = trans.getString("src");
						String dst = trans.getString("dst");
						try {
							src = URLDecoder.decode(src,UTF8);
							dst = URLDecoder.decode(dst,UTF8);
							Log.e("结果：",src+"//"+dst);

							Translate translate = new Translate();
							translate.setFromid(message.getFrom());
							translate.setMsgid(message.getMsgId());
							translate.setDst(dst);
							translate.setSrc(src);
							translate.setMto(to);
							translate.setMfrom(from);
							TranslateDao translateDao = new TranslateDao(mContext);
//							Translate translate1 = translateDao.getTranslateDao(message.getMsgId());
//							String id = translate1.getMsgid();
							if (null==translateDao.getTranslateDao(message.getMsgId()).getMsgid()){
								translateDao.saveTranslateDao(translate);
								listener.onSaveClick(translate);
							}else {
								ContentValues values = new ContentValues();
								values.put(TranslateDao.COLUMN_NAME_DSC, dst);
								translateDao.updateTranslateDao(message.getMsgId(),values);
//								translateDao.deleteOneTranslateDao(message.getMsgId());
								translateDao.saveTranslateDao(translate);
								listener.onUpdateClick(translate);
							}



//							SjtHelper.getInstance().setBaiduTranslateServer(true);
						}catch (UnsupportedEncodingException ex) {
							throw new RuntimeException("Broken VM does not support UTF-8");
						}
					}
//					String code = res.getString("error_code");
//					String message = res.getString("error_msg");
//					if (code.equals("52000")) {//成功
//
//
//
//					} else {//失败
//						TipUtil.showToast(message, mContext, 1);
//					}
				} catch (JSONException ex) {
					ex.printStackTrace();
//					TipUtil.showToast(mContext.getResources().getString(R.string.error_service), mContext, 1);
				}

				TipUtil.closeProgressDialog();
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				TipUtil.showToast(mContext.getResources().getString(R.string.error_network), mContext, 1);
				TipUtil.closeProgressDialog();
			}
		}) {
			@Override
			public Map<String, String> getHeaders() throws AuthFailureError
			{
				Map<String, String> headers = new HashMap<String, String>();
				headers.put("Charset", "UTF-8");
				headers.put("Content-Type", "application/x-javascript");
				headers.put("Accept-Encoding", "gzip,deflate");
				return headers;
			}
		};
		mQueue.add(stringRequest);
	}
}
